package com.touchfired.common.core.listener.impl;

import com.alibaba.fastjson.JSONObject;
import com.touchfired.common.constants.ClientInfo;
import com.touchfired.common.constants.RoomInfo;
import com.touchfired.common.context.ServerContext;
import com.touchfired.common.core.callback.Callback;
import com.touchfired.common.core.event.impl.SendRoomDetailEvent;
import com.touchfired.common.core.listener.BaseListener;
import com.touchfired.common.params.RoomRespInfo;
import com.touchfired.common.utils.RoomUtil;
import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 客户端连接监听器
 *
 * @author 幸佳俊
 */
@Component
public class SendRoomDetailListener extends BaseListener<SendRoomDetailEvent> {

    @Override
    public void onEvent(SendRoomDetailEvent event, Callback callback) {
        RoomInfo roomInfo = event.getRoomInfo();
        if (roomInfo != null) {
            RoomRespInfo respInfo = RoomUtil.converter(roomInfo);
            String roomInfoJson = JSONObject.toJSONString(respInfo);
            List<ClientInfo> roomClients = respInfo.getRoomClients();
            for (ClientInfo clientInfo : roomClients) {
                Channel channel = clientInfo.getChannel();
                if (channel != null) {
                    channel.writeAndFlush(roomInfoJson);
                }
            }
        }
    }
}
